package com.joeyzh.widget;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;

import com.joey.base.util.DataFormatUtils;
import com.joey.base.util.DensityUtil;
import com.joey.ui.widget.ToastHelper;
import com.joeyzh.R;
import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;
import com.prolificinteractive.materialcalendarview.OnDateSelectedListener;

import java.util.Calendar;
import java.util.Date;

/**
 * Created by Joey on 2017/4/19.
 */

public class MyDatePicker extends AppCompatTextView {

    private final String DATE_FORMAT_AND_TIME = "yyyy-MM-dd HH:mm:ss";
    private final String DATE_FORMAT = "yyyy-MM-dd";
    private BottomSheetDialog dlgCalendar;
    private Activity activity;

    /**
     * 用于开始时间和结束时间的绑定
     */
    private MyDatePicker related;
    // 标记是否是开始时间
    private boolean isStartFlag;

    private String dateStr;
    private Date current;
    private TextView tvDate;
    private onDateChangeListener dateChangeListener;
    private DatePicker dpDate;
    private TimePicker tpTime;
    private TextView tvCancel;
    private TextView tvConfirm;
    private Drawable rightDraw;
    // 标记弹窗的类型，有两种：一种是直选日期的，一种是日期和时间都需要选择
    private int type;
    public static final int TYPE_DATE_AND_TIME = 0;
    public static final int TYPE_DATE = 1;
    private MaterialCalendarView calendarView;

    private DatePicker.OnDateChangedListener onDateChangedListener;


    public MyDatePicker(Context context) {
        this(context, null);
    }

    public MyDatePicker(Context context, AttributeSet attrs) {
        this(context, attrs, -1);
    }

    public MyDatePicker(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyDatePicker, defStyleAttr, 0);
        type = a.getInt(R.styleable.MyDatePicker_type, TYPE_DATE_AND_TIME);
        a.recycle();
        init(context);

    }

    private void init(Context context) {
        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                show();
            }
        });
        if (context instanceof Activity) {
            switch (type) {
                case TYPE_DATE:
                    createCalendar((Activity) context);
                    break;
                default:
                    createDialog((Activity) context);
                    break;
            }
        }
        rightDraw = context.getResources().getDrawable(R.drawable.ic_calendar);
        rightDraw.setBounds(0, 0, rightDraw.getMinimumWidth(), rightDraw.getMinimumHeight());
        setMinHeight(DensityUtil.dip2px(context, 35));
        setCompoundDrawables(null, null, rightDraw, null);
        setCompoundDrawablePadding(DensityUtil.dip2px(context, getResources().getDimension(R.dimen.layout_min_margin)));
        resetDate(Calendar.getInstance());
    }

    public void setType(int type) {
        this.type = type;
        init(getContext());
    }

    /**
     * 关联日期
     *
     * @param date
     * @param flag
     */
    public void relateDate(MyDatePicker date, boolean flag) {
        this.related = date;
        isStartFlag = flag;
    }

    // 以当前时间日期为开始，day天数为间隔
    public void resetDateWithDayInterval(int day) {
        Calendar calendar = Calendar.getInstance();
        resetDateWithDayInterval(calendar, day);
    }

    // 以当前时间日期为开始，day天数为间隔
    public void resetDateWithDayInterval(Calendar calendar, int day) {
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE, day);
        resetDate(calendar);
    }


    public void createDialog(final Activity activity) {
        this.activity = activity;
        View view = View.inflate(activity, R.layout.ifr_dlg_date, null);
        dpDate = view.findViewById(R.id.dp_date);
        tpTime = view.findViewById(R.id.tp_time);
        tvCancel = view.findViewById(R.id.tv_cancel);
        tvConfirm = view.findViewById(R.id.tv_confirm);
        tpTime.setIs24HourView(true);
        dlgCalendar = new BottomSheetDialog(activity);
        dlgCalendar.setContentView(view);
        tvDate = (TextView) view.findViewById(R.id.tv_calendar_date);

        dlgCalendar.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                tvDate.setText(dateStr);
                setText(dateStr);
            }
        });
        tvCancel.setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dateStr = getText().toString();
                        setCurrent(dateStr);
                        dismiss();
                    }
                });
        tvConfirm.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });
        tpTime.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
            @Override
            public void onTimeChanged(TimePicker timePicker, int hour, int minute) {
                Date date = new Date(dpDate.getYear() - 1900, dpDate.getMonth(), dpDate.getDayOfMonth(), hour, minute);
                if (!checkInfo(date)) {
                    String msg = isStartFlag ? "开始时间不能大于结束时间！" : "结束时间不能小于开始时间！";
                    ToastHelper.show(activity, msg);
                    return;
                }
                setTitle(date);
                setCurrent(dateStr);
                if (dateChangeListener != null) {
                    dateChangeListener.onChange(dateStr, current);
                }
            }
        });

        onDateChangedListener = new DatePicker.OnDateChangedListener() {
            @Override
            public void onDateChanged(DatePicker datePicker, int year, int month, int day) {
                Date date = new Date(year - 1900, month, day, tpTime.getCurrentHour(), tpTime.getCurrentMinute());
                if (!checkInfo(date)) {
                    String msg = isStartFlag ? "开始时间不能大于结束时间！" : "结束时间不能小于开始时间！";
                    ToastHelper.show(activity, msg);
                    return;
                }
                setTitle(date);
                setCurrent(dateStr);
                if (dateChangeListener != null) {
                    dateChangeListener.onChange(dateStr, current);
                }
            }
        };
    }

    public void createCalendar(final Activity activity) {
        this.activity = activity;
        View view = View.inflate(activity, R.layout.ifr_dlg_calendar, null);
        dlgCalendar = new BottomSheetDialog(activity);
        dlgCalendar.setContentView(view);
        calendarView = view.findViewById(R.id.calendarView);
        tvDate = (TextView) view.findViewById(R.id.tv_calendar_date);
        calendarView.setOnDateChangedListener(new OnDateSelectedListener() {
            @Override
            public void onDateSelected(@NonNull MaterialCalendarView widget, @NonNull CalendarDay calendar, boolean selected) {
                if (!checkInfo(calendar.getDate())) {
                    String msg = isStartFlag ? "开始时间不能大于结束时间！" : "结束时间不能小于开始时间！";
                    ToastHelper.show(activity, msg);
                    return;
                }
                setTitle(calendar.getDate());
                setCurrent(dateStr);
                setText(dateStr);
                if (dateChangeListener != null) {
                    dateChangeListener.onChange(dateStr, current);
                }
                dismiss();
            }
        });
    }

    public void setDateChangeListener(onDateChangeListener dateChangeListener) {
        this.dateChangeListener = dateChangeListener;
    }

    public void show() {
        show(dateStr);
    }

    public void show(String dateStr) {
        if (TextUtils.isEmpty(dateStr)) {
            dlgCalendar.show();
            return;
        }
        this.dateStr = dateStr;
        tvDate.setText(dateStr);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(current);
        resetDate(calendar);
        dlgCalendar.show();
    }

    public void dismiss() {
        dlgCalendar.dismiss();
    }

    /**
     * 取消事件/设置时间
     */
    private void setCurrent(String dateStr1) {
        if (type == TYPE_DATE_AND_TIME) {
            current = DataFormatUtils.convertStrToDate(dateStr1, DATE_FORMAT_AND_TIME);
        } else {
            current = DataFormatUtils.convertStrToDate(dateStr1, DATE_FORMAT);
        }
    }


    private void setTitle(Date date) {
        if (type == TYPE_DATE_AND_TIME) {
            dateStr = DataFormatUtils.convertDateToStr(date, DATE_FORMAT_AND_TIME);
        } else {
            dateStr = DataFormatUtils.convertDateToStr(date, DATE_FORMAT);
        }
        tvDate.setText(dateStr);
    }

    /**
     * 时间默认选中
     */
    public void setCurrentTime(String dateStr) {
        setCurrent(dateStr);
        setTitle(current);
        resetDate(dataToCalendar(current));
    }

    /**
     * 时间默认选中
     */
    public void setCurrentTime(Date current) {
        this.current = current;
        setTitle(current);
        resetDate(dataToCalendar(current));
    }

    //时间转换
    public static Calendar dataToCalendar(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar;
    }

    private boolean checkInfo(Date seleted) {
        if (related == null) {
            return true;
        }
        int compare = seleted.compareTo(related.getActualDate());
        if (compare > 0) {
            return isStartFlag ? false : true;
        } else if (compare < 0) {
            return isStartFlag ? true : false;
        }
        return true;

    }

    public String getDateStr() {
        return dateStr;
    }

    private void resetDate(Calendar calendar) {
        if (TYPE_DATE_AND_TIME == type) {
            int year = calendar.get(Calendar.YEAR);
            int monthOfYear = calendar.get(Calendar.MONTH);
            int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            int minute = calendar.get(Calendar.MINUTE);
            dpDate.init(year, monthOfYear, dayOfMonth, onDateChangedListener);
            tpTime.setCurrentHour(hour);
            tpTime.setCurrentMinute(minute);
        } else {
            calendarView.setSelectedDate(calendar);
        }
        current = calendar.getTime();
        setTitle(current);
        setText(dateStr);
    }

    public Date getActualDate() {
        return current;
    }

    public interface onDateChangeListener {
        void onChange(String dataStr, Date date);
    }

}
